'''
Created on Feb 7, 2012

@author: cgiacofe
'''

from xml.etree import ElementTree as ET
import logxml
import time

filename = 'vpnlog.xml'

# XML tags
SERVER = 'server'
UPTIME = 'uptime'
ISP_IP = 'isp_ip'
VPN_IP = 'vpn_ip'
TIMESTAMP = 'timestamp'
START = 'start_time'
END = 'end_time'
ERROR = 'error'
VERSION = 'version'

class Ddict(dict):
    def __init__(self, default=None):
        self.default = default

    def __getitem__(self, key):
        if not self.has_key(key):
            self[key] = self.default()
        return dict.__getitem__(self, key)


server_stats = Ddict( dict )
root = ET.parse(filename).getroot()

for subelement in root:

    server = subelement.find(SERVER).text
    uptime = float(subelement.find(END).text) - float(subelement.find(START).text)
    error = subelement.find(ERROR).text
    try:
        if uptime < server_stats[server]['min_uptime']:
            server_stats[server]['min_uptime'] = uptime
        if uptime > server_stats[server]['max_uptime']:
            server_stats[server]['max_uptime'] = uptime
    except:
        server_stats[server]['min_uptime'] = uptime
        server_stats[server]['max_uptime'] = uptime
    
    # Increment server run counter
    try:
        server_stats[server]['count'] += 1
        server_stats[server]['total_uptime'] += uptime
    except:
        server_stats[server]['count'] = 1
        server_stats[server]['total_uptime'] = uptime
        
    server_stats[server]['average_uptime'] = server_stats[server]['total_uptime'] / server_stats[server]['count']
    
    if error != 'Server Switch':
        try:
            server_stats[server]['error'] += 1
        except:
            server_stats[server]['error'] = 1
    else:
        try:
            server_stats[server]['error'] += 0
        except:
            server_stats[server]['error'] = 0        
    
filename = 'stats' + str(time.time()) + '.xml'

stats = []
for key in server_stats:
    server_stats[key]['server'] = key
    stats.append(server_stats[key])
    
logxml.write_log(stats, filename)